package com.test.dao;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

import org.springframework.dao.DataAccessException;
import org.springframework.jdbc.core.PreparedStatementCallback;
import org.springframework.jdbc.core.PreparedStatementCreator;
import org.springframework.jdbc.core.RowCallbackHandler;
import org.springframework.jdbc.core.RowMapper;
import org.springframework.stereotype.Repository;

import com.test.model.UserInfo;

@Repository("userInfoDao")
public class UserDao extends BaseDao
{
	/**
	 * jdbcTemplate的用法详见博文:http://blog.csdn.net/dyllove98/article/details/
	 * 7772463
	 * @param sql
	 * @return Created: 2015年2月26日
	 * @author: Penghao
	 */
	public UserInfo findBean(String sql, Object... params)
	{
		return jdbcTemplate.queryForObject(sql, params, new RowMapper<UserInfo>()
		{
			@Override
			public UserInfo mapRow(ResultSet rs, int rowNum) throws SQLException
			{
				UserInfo user = new UserInfo();
				user.setId(rs.getInt("id"));
				user.setAccount(rs.getString("account"));
				user.setNickname(rs.getString("nickname"));
				user.setId(rs.getInt("role"));
				return user;
			}
		});
	}

	public List<UserInfo> findBeanList(String sql)
	{
		final List<UserInfo> users = new ArrayList<UserInfo>();
		jdbcTemplate.query(sql, new RowCallbackHandler()
		{
			@Override
			public void processRow(ResultSet resultset) throws SQLException
			{
				UserInfo user = new UserInfo();
				user.setId(resultset.getInt("id"));
				user.setAccount(resultset.getString("account"));
				user.setNickname(resultset.getString("nickname"));
				users.add(user);
			}
		});
		return users;
	}

	public List<UserInfo> findBeanList(final String sql, final Object param)
	{
		final List<UserInfo> users = new ArrayList<UserInfo>();
		jdbcTemplate.query(new PreparedStatementCreator()
		{
			@Override
			public PreparedStatement createPreparedStatement(Connection arg0) throws SQLException
			{
				PreparedStatement stmt = arg0.prepareStatement(sql);
				stmt.setObject(1, param);
				return stmt;
			}
		}, new RowCallbackHandler()
		{
			@Override
			public void processRow(ResultSet resultset) throws SQLException
			{
				UserInfo user = new UserInfo();
				user.setId(resultset.getInt("id"));
				user.setAccount(resultset.getString("account"));
				user.setNickname(resultset.getString("nickname"));
				users.add(user);
			}
		});
		return users;
	}
	
}
